package com.leetcode.algorithm.y22.m07;

import java.util.Arrays;

/**
 * 350. 两个数组的交集 II
 * 
 * https://leetcode.cn/problems/intersection-of-two-arrays-ii/
 * 
 * @author jie.deng
 *
 */
public class Question0350Solution01 {
    
	public int[] intersect(int[] nums1, int[] nums2) {
		Arrays.sort(nums1);
		Arrays.sort(nums2);

		int len1 = nums1.length;
		int len2 = nums2.length;
		int[] tmpArr = new int[Math.min(len1, len2)];

		int idx1 = 0;
		int idx2 = 0;
		int idx = 0;
		while (idx1 < len1 && idx2 < len2) {
			if (nums1[idx1] == nums2[idx2]) {
				tmpArr[idx++] = nums1[idx1];
				idx1++;
				idx2++;
			} else if (nums1[idx1] > nums2[idx2]) {
				idx2++;
			} else {
				idx1++;
			}
		}

		int[] retArr = new int[idx];
		for (int i = 0; i < idx; i++) {
			retArr[i] = tmpArr[i];
		}
		return retArr;
	}
    
}
